package com.zulu.karaoke.gui;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

import android.content.Context;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.SystemClock;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.Spinner;
import android.widget.TextView;

import com.zulu.karaoke.R;
import com.zulu.karaoke.actionbar.ActionModeHelper;
import com.zulu.karaoke.adapter.ListSongAdapter;
import com.zulu.karaoke.constants.CommonConstants;
import com.zulu.karaoke.database.DatabaseManager;
import com.zulu.karaoke.database.SongTableHelper;
import com.zulu.karaoke.gui.custom.CustomAlertDialog;
import com.zulu.karaoke.model.SongModel;
import com.zulu.karaoke.utils.GeneralUtils;

public class FragmentFullListSong extends Fragment{

	private Context mContext;
	private ListView mLstViewSong;
	private Spinner mSpnVolList;
	private Spinner mSpnAlphaList;
	private Button mBtnGoTop;
	private static FragmentFullListSong instance;
	
	private SongTableHelper insSongHelper;
	private List<String> lstNumber;
	private List<String> lstTitle;
	private List<String> lstFavourite;
	
	private final static String TAG = "ListSongFull";
	
	private ListSongAdapter adapter;
	
	public static FragmentFullListSong getInstance(){
		if(instance == null) {
			instance = new FragmentFullListSong();
		}
		return instance;
	}
	
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		
//		return super.onCreateView(inflater, container, savedInstanceState);
		mContext = this.getActivity();
		insSongHelper = DatabaseManager.getInstance().getSongTableHelper();
		
		if (insSongHelper.getAllNumber().isEmpty()) {
			try {
				
				showDialogConfirmGetDataFirstTime();
				
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		
		final View view = inflater.inflate(R.layout.fragment_full_song_list, null);
		mLstViewSong = (ListView)view.findViewById(R.id.lst_view_song);
		mSpnVolList = (Spinner) view.findViewById(R.id.spn_vol_list_full);
		mSpnAlphaList = (Spinner) view.findViewById(R.id.spn_alpha_list_full);
		mBtnGoTop = (Button)view.findViewById(R.id.btn_go_top);
		getVolList();
		getVolAlpha();
		
		getDefaultListSongToAdapter();
		
		mLstViewSong.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> l, View v, int position, long id) {
				
				GeneralUtils.showPopupSongDetail(mContext, insSongHelper, 
						lstNumber, position, adapter);
				
			}
		});
		
		mLstViewSong.setOnItemLongClickListener(new ActionModeHelper(this, mLstViewSong, lstTitle, lstNumber));
		
		mSpnVolList.setOnItemSelectedListener(new OnItemSelectedListener() {

			@Override
			public void onItemSelected(AdapterView<?> arg0, View view, int pos,
					long arg3) {
				mSpnAlphaList.setSelection(0);
				getSongForVolSelected(pos);
			}

			@Override
			public void onNothingSelected(AdapterView<?> arg0) {
				

			}
		});
		
		mSpnAlphaList.setOnItemSelectedListener(new OnItemSelectedListener() {

			@Override
			public void onItemSelected(AdapterView<?> l, View arg1, int pos, long id) {
				
				getSongForVolAndAlphaSelected(mSpnVolList.getSelectedItemPosition(), l.getSelectedItem().toString().toLowerCase());
			}

			@Override
			public void onNothingSelected(AdapterView<?> arg0) {
				
			}
		});
		
		mBtnGoTop.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View arg0) {
				mSpnAlphaList.setSelection(0);
				refreshAdapterList();
			}
		});
		
		return view;
	}
	
	public boolean performAction(MenuItem item, int position) {
//		ArrayAdapter<String> adapter = (ArrayAdapter<String>) getListAdapter();

		switch (item.getItemId()) {
		case R.id.view_song:
			GeneralUtils.showPopupSongDetail(mContext, insSongHelper, 
					lstNumber, position, adapter);
			return (true);
		case R.id.like_song:
			final SongModel song = insSongHelper.getSongObjectBaseNumber(lstNumber.get(position));
			if(song.getSongFavourite().equals("1")) {
				GeneralUtils.showToastMessage(mContext, getActivity().getString(R.string.mess_favourite_exist));
			} else {
				song.setSongFavourite("1");
				insSongHelper.updateSong(song);
				GeneralUtils.showToastAddFavouriteDone(mContext);
			}
			return (true);
		}

		return (false);
	}
	
	private void showDialogConfirmGetDataFirstTime() {

		final View childView = LayoutInflater.from(getActivity()).inflate(R.layout.custom_dialog_simple_layout, null, false);
		TextView textView = (TextView)childView.findViewById(R.id.tv_mess_content);
		textView.setText(getActivity().getString(R.string.mess_add_data_confirm));
		final CustomAlertDialog alert = new CustomAlertDialog(getActivity(), childView, true);
		alert.setTitle(getActivity().getString(R.string.title_add_data_confirm));
		alert.setButton(getActivity().getString(R.string.button_text_ok), new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				alert.hideDialog();
				new ProgressTaskGetDataShowDialog().execute();
				
			}
		});
		alert.setButton2(getActivity().getString(R.string.button_text_later), new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				alert.hideDialog();
				getActivity().finish();
			}
		});
		alert.showDialog();
	
	}
	
	public class ProgressTaskGetDataShowDialog extends AsyncTask<Void, Integer, Void> {
		
		View progressView;
		ProgressBar percentProgress;
		ProgressBar percentLoading;
		TextView textUpdateStatus;
		CustomAlertDialog alertProgressDialog;
		int myProgress;
		
		private void initViewForProgressDialog() {
			progressView = LayoutInflater.from(getActivity()).inflate(R.layout.custom_progress_dialog, null, false);
			percentProgress = (ProgressBar)progressView.findViewById(R.id.progressBar1);
			percentLoading = (ProgressBar)progressView.findViewById(R.id.progressBar2);
			textUpdateStatus = (TextView)progressView.findViewById(R.id.tv_update_data_status);
			percentLoading.setVisibility(View.VISIBLE);        
			percentProgress.setProgress(0);
			percentLoading.setSecondaryProgress(0);
			
			alertProgressDialog = new CustomAlertDialog(mContext, progressView, false);
			alertProgressDialog.setTitle(getActivity().getString(R.string.title_data_add_progress));
		}
		
		@Override
		protected void onPreExecute() {
			initViewForProgressDialog();
			myProgress = 0;
			percentProgress.setSecondaryProgress(0);
			alertProgressDialog.showDialog();
		}

		@Override
		protected Void doInBackground(Void... params) {
			// TODO Auto-generated method stub
			if (params == null) {
				return null;
			}

			try {
				getAllSongVol46FromFile();
				getAllSongVol47FromFile();
				getAllSongVol45FullFromFile();
				getAllSongEnglishFromFile();
				while (myProgress < 100) {
					myProgress++;
					publishProgress(myProgress);
					SystemClock.sleep(100);
				}
			} catch (Exception e) {
				Log.i(TAG, e.getMessage());
				return null;
			}

			return null;
		}
		
		@Override
		protected void onPostExecute(Void result) {
			alertProgressDialog.hideDialog();
			GeneralUtils.showToastMessageLongTime(getActivity(), getActivity().getString(R.string.mess_add_data_done));
			getDefaultListSongToAdapter();
		}
		
		@Override
		protected void onProgressUpdate(Integer... values) {
			percentProgress.setProgress(values[0]);
			percentProgress.setSecondaryProgress(values[0] + 2);
			textUpdateStatus.setText(getActivity().getString(R.string.title_saving_data));
		}
		
	}
	
//	public class ProgressTaskGetData extends AsyncTask<Void, Integer, Void> {
//		
//		@Override
//		protected void onPreExecute() {
//			
//		}
//
//		@Override
//		protected Void doInBackground(Void... params) {
//			// TODO Auto-generated method stub
//			if (params == null) {
//				return null;
//			}
//			try {
//				Thread.sleep(1000);
////				getAllSongVol46FromFile();
//				getAllSongVol47FromFile();
////				getAllSongVol45FullFromFile();
////				getAllSongEnglishFromFile();
////				getDefaultListSongToAdapter();
//				
//			} catch (Exception e) {
//				Log.i(TAG, e.getMessage());
//				return null;
//			}
//			
//			return null;
//		}
//		
//		@Override
//		protected void onPostExecute(Void result) {
//			GeneralUtils.showToastMessageLongTime(getActivity(), getActivity().getString(R.string.mess_add_data_done));
//		}
//	}
	
	private void getSongForVolSelected(int pos) {
//		Toast.makeText(mContext, mSpnVolList.getItemAtPosition(pos).toString(),
//				Toast.LENGTH_SHORT).show();
		adapter = new ListSongAdapter(mContext,
				getListNumberForCategory(CommonConstants.getCategoryFromSpinner(pos)),
				getListTitleForCategory(CommonConstants.getCategoryFromSpinner(pos)),
				getListFavouriteNumber());
		adapter.setNotifyOnChange(true);
		mLstViewSong.setAdapter(adapter);
		mLstViewSong.setOnItemLongClickListener(new ActionModeHelper(this, mLstViewSong, lstTitle, lstNumber));

	}
	
	private void getSongForVolAndAlphaSelected(int pos, String alpha) {
		if(alpha.equals(CommonConstants.getListAlpha().get(0).toLowerCase())) {
			getSongForVolSelected(pos);
		} else {
			adapter = new ListSongAdapter(mContext,
					getListNumberForCategoryAlpha(CommonConstants.getCategoryFromSpinner(pos), alpha),
					getListTitleForCategoryAlpha(CommonConstants.getCategoryFromSpinner(pos), alpha),
					getListFavouriteNumber());
			adapter.setNotifyOnChange(true);
			mLstViewSong.setAdapter(adapter);
			mLstViewSong.setOnItemLongClickListener(new ActionModeHelper(this, mLstViewSong, lstTitle, lstNumber));
		}
	}
	
	private void refreshAdapterList() {
		adapter = new ListSongAdapter(mContext,
				getListNumberForCategory(CommonConstants.getCategoryFromSpinner(this.mSpnVolList.getSelectedItemPosition())),
				getListTitleForCategory(CommonConstants.getCategoryFromSpinner(this.mSpnVolList.getSelectedItemPosition())),
				getListFavouriteNumber());
		mLstViewSong.setAdapter(adapter);
	}
	
	private void getDefaultListSongToAdapter() {
		adapter = new ListSongAdapter(mContext,
				getListNumberForCategory(CommonConstants.CategoryConstants.VOL47),
				getListTitleForCategory(CommonConstants.CategoryConstants.VOL47),
				getListFavouriteNumber());
		adapter.setNotifyOnChange(true);
		mLstViewSong.setAdapter(adapter);
	}
	
	private void getVolList() {
		ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(mContext,
				R.layout.mysimple_spinner_item, CommonConstants.getListVol());

		dataAdapter.setDropDownViewResource(R.layout.mysimple_spinner_view);
		mSpnVolList.setAdapter(dataAdapter);
	}

	private void getVolAlpha() {
		ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(mContext,
				R.layout.mysimple_spinner_item, CommonConstants.getListAlpha());

		dataAdapter.setDropDownViewResource(R.layout.mysimple_spinner_view);
		mSpnAlphaList.setAdapter(dataAdapter);
	}
	
	private String[] getListTitleForCategory(String category) {
		lstTitle = new ArrayList<String>();
		lstTitle = insSongHelper.getAllTitleBaseCategory(category);
		String[] result = new String[lstTitle.size()];
		for (int i = 0; i < lstTitle.size(); i++) {
			result[i] = lstTitle.get(i);
		}
		return result;
	}
	
	private String[] getListTitleForCategoryAlpha(String category, String alpha) {
		lstTitle = new ArrayList<String>();
		lstTitle = insSongHelper.getAllTitleBaseCategoryAlpha(category, alpha);
		String[] result = new String[lstTitle.size()];
		for (int i = 0; i < lstTitle.size(); i++) {
			result[i] = lstTitle.get(i);
		}
		return result;
	}

	private String[] getListNumberForCategory(String category) {
		lstNumber = new ArrayList<String>();
		lstNumber = insSongHelper.getAllNumberBaseCalegory(category);
		String[] result = new String[lstNumber.size()];
		for (int i = 0; i < lstNumber.size(); i++) {
			result[i] = lstNumber.get(i);
		}
		return result;
	}
	
	private String[] getListNumberForCategoryAlpha(String category, String alpha) {
		lstNumber = new ArrayList<String>();
		lstNumber = insSongHelper.getAllNumberBaseCalegoryAlpha(category, alpha);
		String[] result = new String[lstNumber.size()];
		for (int i = 0; i < lstNumber.size(); i++) {
			result[i] = lstNumber.get(i);
		}
		return result;
	}
	
	private String[] getListFavouriteNumber() {
		lstFavourite = new ArrayList<String>();
		lstFavourite = insSongHelper.getAllFavouriteNumber();
		String[] result = new String[lstFavourite.size()];
		for(int i=0;i<lstFavourite.size();i++) {
			result[i] = lstFavourite.get(i);
		}
		return result;
	}
	
	private void getAllSongEnglishFromFile() throws IOException {
		
		String str = "";
		InputStream is = this.getResources().openRawResource(
				R.drawable.listkaraenglish);
		BufferedReader reader = new BufferedReader(new InputStreamReader(is));
		StringBuffer buf = new StringBuffer();	
		if (is != null) {
			while ((str = reader.readLine()) != null) {
				buf.append(str + "<;>" );
			}
			String fullString = buf.toString();
			String[] lstSong = fullString.split("<;>");
			for (String string : lstSong) {
				String[] lstInfo = string.split(";");
				if (lstInfo.length > 2) {
					SongModel song = new SongModel();
					song.setSongTitleSearch(lstInfo[0] != null ? lstInfo[0].toLowerCase() : " ");
					song.setSongTitleFirstChar(lstInfo[0] != null ? lstInfo[0].subSequence(0, 1).toString().toLowerCase() : " ");
					song.setSongBegin(" ");
					song.setSongBeginSearch(" ");
					song.setSongComposer(lstInfo[2] != null ? lstInfo[2] : " ");
					song.setSongComposerSearch(lstInfo[2] != null ? lstInfo[2] : " ");
					song.setSongNumber(lstInfo[1] != null ? lstInfo[1] : " ");
					song.setSongTitle(lstInfo[0] != null ? lstInfo[0] : " ");
					song.setSongCategory(CommonConstants.CategoryConstants.ENGLISH);
					song.setSongFavourite("0");
					insSongHelper.addSong(song);
				} else {
					Log.i(TAG, "Error in vol English: " + lstInfo[0]);
				}
			}
		}
		is.close();
	}
	
	private void getAllSongVol46FromFile() throws IOException {
		
		String str = "";
		InputStream is = this.getResources().openRawResource(
				R.drawable.listvol46);
		BufferedReader reader = new BufferedReader(new InputStreamReader(is));
		StringBuffer buf = new StringBuffer();	
		if (is != null) {
			while ((str = reader.readLine()) != null) {
				buf.append(str + "<;>" );
			}
			String fullString = buf.toString();
			String[] lstSong = fullString.split("<;>");
			for (String string : lstSong) {
				String[] lstInfo = string.split(";");
				if (lstInfo.length == 4) {
					SongModel song = new SongModel();
					song.setSongTitleSearch(lstInfo[1] != null ? convertToSearchableText(lstInfo[1].toLowerCase()) : " ");
					song.setSongTitleFirstChar(lstInfo[1] != null ? convertToSearchableText(lstInfo[1].toLowerCase()).subSequence(0, 1).toString() : " ");
					song.setSongBegin(lstInfo[2] != null ? lstInfo[2] : " ");
					song.setSongBeginSearch(lstInfo[2] != null ? convertToSearchableText(lstInfo[2].toLowerCase()) : " ");
					song.setSongComposer(lstInfo[3] != null ? lstInfo[3] : " ");
					song.setSongComposerSearch(lstInfo[3] != null ? convertToSearchableText(lstInfo[3].toLowerCase()) : " ");
					song.setSongNumber(lstInfo[0] != null ? lstInfo[0] : " ");
					song.setSongTitle(lstInfo[1] != null ? lstInfo[1] : " ");
					song.setSongCategory(CommonConstants.CategoryConstants.VOL46);
					song.setSongFavourite("0");
					insSongHelper.addSong(song);
				} else {
					Log.i(TAG, "Error in vol 46: " + lstInfo[0]);
				}
			}
		}
		is.close();
	}

	private void getAllSongVol47FromFile() throws IOException {
		
		String str = "";
		InputStream is = this.getResources().openRawResource(
				R.drawable.listvol47);
		BufferedReader reader = new BufferedReader(new InputStreamReader(is));
		StringBuffer buf = new StringBuffer();	
		if (is != null) {
			while ((str = reader.readLine()) != null) {
				buf.append(str + "<;>" );
//				String[] lstInfo = str.split(";");
//				if (lstInfo.length > 3) {
//					SongModel song = new SongModel();
//					song.setSongNumber(lstInfo[0] != null ? lstInfo[0] : " ");
//					song.setSongTitle(lstInfo[1] != null ? lstInfo[1] : " ");
//					song.setSongBegin(lstInfo[2] != null ? lstInfo[2] : " ");
//					song.setSongComposer(lstInfo[3] != null ? lstInfo[3] : " ");
//					song.setSongCategory(CommonConstants.CategoryConstants.VOL47);
//					song.setSongFavourite("0");
//					insSongHelper.addSong(song);
//				} else {
//					Log.i(TAG, "Error in: " + lstInfo[0]);
//				}
			}
			String fullString = buf.toString();
			String[] lstSong = fullString.split("<;>");
			for (String string : lstSong) {
				String[] lstInfo = string.split(";");
				if (lstInfo.length == 4) {
					SongModel song = new SongModel();
					song.setSongTitleSearch(lstInfo[1] != null ? convertToSearchableText(lstInfo[1].toLowerCase()) : " ");
					song.setSongTitleFirstChar(lstInfo[1] != null ? convertToSearchableText(lstInfo[1].toLowerCase()).subSequence(0, 1).toString() : " ");
					song.setSongBegin(lstInfo[2] != null ? lstInfo[2] : " ");
					song.setSongBeginSearch(lstInfo[2] != null ? convertToSearchableText(lstInfo[2].toLowerCase()) : " ");
					song.setSongComposer(lstInfo[3] != null ? lstInfo[3] : " ");
					song.setSongComposerSearch(lstInfo[3] != null ? convertToSearchableText(lstInfo[3].toLowerCase()) : " ");
					song.setSongNumber(lstInfo[0] != null ? lstInfo[0] : " ");
					song.setSongTitle(lstInfo[1] != null ? lstInfo[1] : " ");
					song.setSongCategory(CommonConstants.CategoryConstants.VOL47);
					song.setSongFavourite("0");
					insSongHelper.addSong(song);
				} else {
					Log.i(TAG, "Error in vol 47: " + lstInfo[0]);
				}
			}
		}
		is.close();
	}

	private void getAllSongVol45FullFromFile() throws IOException {
		String str = "";
		InputStream is = this.getResources().openRawResource(
				R.drawable.listvol45fullutf);
		BufferedReader reader = new BufferedReader(new InputStreamReader(is));
		StringBuffer buf = new StringBuffer();	
		if (is != null) {
			while ((str = reader.readLine()) != null) {
				buf.append(str + "<;>" );
			}
			String fullString = buf.toString();
			String[] lstSong = fullString.split("<;>");
			for (String string : lstSong) {
				String[] lstInfo = string.split(";");
				if (lstInfo.length > 4) {
					SongModel song = new SongModel();
					song.setSongTitleSearch(lstInfo[0] != null ? lstInfo[0].toLowerCase() : " ");
					song.setSongTitleFirstChar(lstInfo[0] != null ? lstInfo[0].subSequence(0, 1).toString().toLowerCase() : " ");
					song.setSongTitle(lstInfo[1] != null ? lstInfo[1].toUpperCase() : " ");
					song.setSongNumber(lstInfo[2] != null ? lstInfo[2] : " ");
					song.setSongComposer(lstInfo[3] != null ? lstInfo[3] : " ");
					song.setSongComposerSearch(lstInfo[3] != null ? convertToSearchableText(lstInfo[3].toLowerCase()) : " ");
					song.setSongBegin(lstInfo[4] != null ? lstInfo[4] : " ");
					song.setSongBeginSearch(lstInfo[4] != null ? convertToSearchableText(lstInfo[4].toLowerCase()) : " ");
					song.setSongCategory(CommonConstants.CategoryConstants.VOL45FULL);
					song.setSongFavourite("0");
					insSongHelper.addSong(song);
				} else {
					Log.i(TAG, "Error in vol 45full: " + lstInfo[0]);
				}
				if(convertToSearchableText(lstInfo[3].toLowerCase()).equals("tran tien")) {
					Log.i(TAG, "Tran tien: " + lstInfo[0]);
				}
			}
		}
		is.close();
	}
	
	private String convertToSearchableText(String value) {
		String result = "";
		result = value
				.replaceAll("đ", "d")
				.replaceAll("á", "a").replaceAll("à", "a").replaceAll("ã", "a").replaceAll("ả", "a").replaceAll("ạ", "a")
				.replaceAll("í", "i").replaceAll("ì", "i").replaceAll("ĩ", "i").replaceAll("ỉ", "i").replaceAll("ị", "i")
				.replaceAll("é", "e").replaceAll("è", "e").replaceAll("ẽ", "e").replaceAll("ẻ", "e").replaceAll("ẹ", "e")
				.replaceAll("ó", "o").replaceAll("ò", "o").replaceAll("õ", "o").replaceAll("ỏ", "o").replaceAll("ọ", "o")
				.replaceAll("ý", "y").replaceAll("ỳ", "y").replaceAll("ỹ", "y").replaceAll("ỷ", "y").replaceAll("ỵ", "y")
				.replaceAll("ú", "u").replaceAll("ù", "u").replaceAll("ũ", "u").replaceAll("ủ", "u").replaceAll("ụ", "u")
				.replaceAll("ô", "o").replaceAll("ố", "o").replaceAll("ồ", "o").replaceAll("ỗ", "o").replaceAll("ổ", "o").replaceAll("ộ", "o")
				.replaceAll("ơ", "o").replaceAll("ớ", "o").replaceAll("ờ", "o").replaceAll("ỡ", "o").replaceAll("ở", "o").replaceAll("ợ", "o")
				.replaceAll("ư", "u").replaceAll("ứ", "u").replaceAll("ừ", "u").replaceAll("ữ", "u").replaceAll("ử", "u").replaceAll("ự", "u")
				.replaceAll("â", "a").replaceAll("ấ", "a").replaceAll("ầ", "a").replaceAll("ẫ", "a").replaceAll("ẩ", "a").replaceAll("ậ", "a")
				.replaceAll("ă", "a").replaceAll("ắ", "a").replaceAll("ằ", "a").replaceAll("ẵ", "a").replaceAll("ẳ", "a").replaceAll("ặ", "a")
				.replaceAll("ê", "e").replaceAll("ế", "e").replaceAll("ề", "e").replaceAll("ễ", "e").replaceAll("ể", "e").replaceAll("ệ", "e")
					;
		return result;
	}
	
}
